package com.example.mywechat;


import android.Manifest;
import android.app.Fragment;
import android.content.ContentResolver;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;


/**
 * A simple {@link Fragment} subclass.
 */
public class contactFragment extends Fragment {
 // private static final String TAG = contactFragment.class.getSimpleName();

    private ContentResolver contentResolver;//=getContext().getContentResolver();
    private View view;
    private RecyclerView recyclerView;
    private List<ContactDataBean> contactdatabeanList=new ArrayList<>();
    private ContactAdapter contactsAdapter;


    public contactFragment() {
        // Required empty public constructor
    }


    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED)
        {
            ActivityCompat.requestPermissions(this.getActivity(),new String[]{Manifest.permission.READ_CONTACTS},1);
        }

        view= inflater.inflate(R.layout.tab08, container, false);
        return view;
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        ImageButton imageButton=(ImageButton)getActivity().findViewById(R.id.imageButton5);
        imageButton.setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onClick(View v) {
                fun();
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    }


    @RequiresApi(api = Build.VERSION_CODES.M)
    public void fun(){
        recyclerView=(RecyclerView)getActivity().findViewById(R.id.rcv_contacts);

        //获取手机联系人的Uri,相当于提供了一个公共的数据库链接
        Uri uri= ContactsContract.Contacts.CONTENT_URI;//内部类静态成员
        //android.content.Context提供了抽象方法getContentResolver()方法
        //通过内容（数据）解析器使用抽象类android.content.ContentResolver提供了query()等方法
        Cursor cursor=getContext().getContentResolver().query(uri, null, null, null, null);  //得到记录集
        while(cursor.moveToNext()){
            //先获取联系人_id字段的索引号后再获取_id值
            int idFieldIndex=cursor.getColumnIndex("_id");//法一
            //int idFieldIndex=cursor.getColumnIndex(ContactsContract.Contacts._ID);//法二
            int id=cursor.getInt(idFieldIndex);

            //先获取联系人姓名字段的索引号后再获取姓名字段值
            int nameFieldIndex  = cursor.getColumnIndex("display_name");
            //int nameFieldIndex=cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
            String name=cursor.getString(nameFieldIndex);

            int numCountFieldIndex=cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER);
            int numCount=cursor.getInt(numCountFieldIndex);   //获取联系人的电话号码个数
            String phoneNumber="";
            if(numCount>0){       //联系人有至少一个电话号码
                //在类ContactsContract.CommonDataKinds.Phone中根据id查询相应联系人的所有电话；
                Cursor phonecursor=getContext().getContentResolver().query(
                        ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                        null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID+"=?",
                        new String[]{Integer.toString(id)}, null);
                if(phonecursor.moveToFirst()){     //仅读取第一个电话号码
                    int numFieldIndex=phonecursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
                    phoneNumber=phonecursor.getString(numFieldIndex);
                }
            }

            //必须在循环中创建
            ContactDataBean contactdatabean=new ContactDataBean();
            contactdatabean.setName(name);
            contactdatabean.setPhoneNumber(phoneNumber);
            Log.d("Phone","hhhhh"+phoneNumber);
            contactdatabeanList.add(contactdatabean);
        }

        contactsAdapter=new ContactAdapter(getContext(),contactdatabeanList);
        recyclerView.setAdapter(contactsAdapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        // recyclerView.setHasFixedSize(true);

    }

}
